import json
import numpy as n
from machine import *

STORE = "/netflix/stats/"
    
class Stats(object):
  def __init__(self, tr, store):
    self.tr = tr
    self.store = store
    self.basic_movie = {}
    self.basic_user = {}
    self.adv_movie = {}
    self.adv_user = {}
  def make_basic_stats(self):
    for mid in self.tr.movieIDs():
      rs = tr.movie(mid).ratings()
      self.basic_movie[int(mid)] = (n.mean(rs), n.std(rs))
    for uid in self.tr.userIDs():
      rs = tr.user(uid).ratings()
      self.basic_user[int(uid)] = (n.mean(rs), n.std(rs))
      
  def make_adv_stats(self):
    for mid in self.tr.movieIDs():
      m = self.tr.movie(mid)
      users = m.values()
      ratings = m.ratings()
      diff_rs = [self.basic_user[u][0] - r for u, r in zip(users, ratings)]
      self.adv_movie[int(mid)] = (n.mean(diff_rs), n.std(diff_rs))
    for uid in self.tr.userIDs():
      u = self.tr.user(uid)
      movies = u.values()
      ratings = u.ratings()
      diff_rs = [self.basic_movie[m][0] - r for m, r in zip(movies, ratings)]
      self.adv_user[int(uid)] = (n.mean(diff_rs), n.std(diff_rs))
  
  def write_data(self):
    for datum, fn in [(self.basic_movie, "bm"), (self.basic_user, "bu"),
                      (self.adv_movie, "am"), (self.adv_user, "au")]:
      f = file(self.store + fn, 'w')
      json.dump(datum, f)
      f.close()
  
  def read_data(self):
    for datum, fn in [(self.basic_movie, "bm"), (self.basic_user, "bu"),
                      (self.adv_movie, "am"), (self.adv_user, "au")]:
      datum.update(json.load(file(self.store + fn)))
      for key in datum.keys():
        datum[int(key)] = datum[key]
        del datum[key]
    